import {
  ALL,
  Body,
  Config,
  Controller,
  Get,
  Inject,
  Post,
  Provide,
  Validate,
} from '@midwayjs/decorator';
import { Context } from '@midwayjs/koa';
import { LoginDto } from '../dto';
import { User } from '../entity/User';
import { UserService } from '../service/user';
import * as jwt from 'jsonwebtoken';
import * as _ from 'lodash';
import { Repository } from 'typeorm';
import { InjectEntityModel } from '@midwayjs/orm';

@Provide()
@Controller('/auth', { tagName: '鉴权接口' })
export class AuthController {
  @Inject()
  ctx: Context;

  @Inject()
  userService: UserService;

  @InjectEntityModel(User)
  userModel: Repository<User>;

  @Config('jwt')
  jwtConfig;

  @Post('/login', { summary: '登录接口' })
  @Validate()
  async login(@Body(ALL) body: LoginDto) {
    const user = await this.userModel.findOne({ username: body.username });
    if (!user || !user.validatePassword(body.password)) {
      this.ctx.throw(400, '用户名或密码错误');
    }
    const token = jwt.sign(
      _.pick(user, ['id', 'nickname', 'avatarUrl', 'integral']),
      this.jwtConfig.secret
    );
    return { token, user };
  }

  @Get('/me', { middleware: ['jwt'], summary: '获取个人信息' })
  async me() {
    return this.ctx.state.user;
  }
}
